/**
 * bushaofeng. 2011.8.26
 * bs_array.c
 * history:
 */

#include "bs_struct.h"

int _bs_array_init(_bs_array_t* array, size_t esize){
    if(array == NULL){
        return BS_PARAERR;
    }

    array->esize = esize;
    array->elem = malloc(array->esize * BS_DEF_ARYLEN);
    if(array->elem == NULL){
        return BS_NOMEM;
    }
    
    memset(array->elem, 0, array->esize*BS_DEF_ARYLEN);
    array->size = BS_DEF_ARYLEN;
    array->len = 0;

    return BS_SUCCESS;
}

int _bs_array_init_len(_bs_array_t* array, size_t esize, int len){
    if(array == NULL || esize <=0 || len<= 0){
        return BS_PARAERR;
    }

    array->esize = esize;
    array->elem = malloc(array->esize * len);
    if(array->elem == NULL){
        return BS_NOMEM;
    }
    array->size = len;
    array->len = 0;

    return BS_SUCCESS;
}

int _bs_array_add(_bs_array_t* array, void* elem, size_t esize){
    void*       pnew;
    char*       pcopy;
    
    if(array==NULL || elem==NULL || esize!=array->esize){
        return BS_PARAERR;
    }

    if(array->len >= array->size){
        pnew = realloc(array->elem, (array->len+BS_DEF_ADDLEN)*esize);
        if(pnew == NULL){
            return BS_NOMEM;
        }

        free(array->elem);
        array->elem = pnew;
        array->size += BS_DEF_ADDLEN;
    }

    pcopy = (char*)array->elem + array->len * esize;
    memcpy(pcopy, elem, esize);
    array->len++;

    return BS_SUCCESS;
}

int _bs_array_get(_bs_array_t* array, void* elem, uint32_t i){
    if(array == NULL || elem == NULL || i >= array->len){
        return BS_PARAERR;
    }

    memcpy(elem, (char*)array->elem + array->esize*i, array->esize);
    return BS_SUCCESS;
}

void* _bs_array_get_ptr(_bs_array_t* array, uint32_t i){
    if(array == NULL || i >= array->len){
        return NULL;
    }

    return (char*)array->elem + array->esize*i;
}
